/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { catalog } from "@mall/api-services"
import classNames from "classnames"
import * as _ from "lodash"
import * as React from "react"
import LazyLoad from "react-lazyload"
import Flex from "../components/flex"
import NavBar from "../components/navbar"
import Scroll from "../components/scroll"

import "./index.scss"

interface TertiaryCategoryProps {
  category: catalog.Category;
}

class TertiaryCategory extends React.Component<TertiaryCategoryProps> {

  public render() {
    const { category } = this.props
    return (
      <div className="tertiary-category">
        <Flex alignItems="center" direction="column" justifyContent="center">
          <LazyLoad height="100%" offset={100} overflow once>
            <img className="tertiary-category-icon" src={category.imageUrl} alt=""/>
          </LazyLoad>
          <span className="tertiary-category-name">{category.name}</span>
        </Flex>
      </div>
    )
  }
}

interface SecondaryCategoryProps {
  category: catalog.Category;
}

interface SecondaryCategoryState {
}

class SecondaryCategory extends React.Component<SecondaryCategoryProps, SecondaryCategoryState> {

  public constructor(props: Readonly<SecondaryCategoryProps>) {
    super(props)
    this.state = {}
  }

  public render() {
    const { category } = this.props
    return (
      <div className="secondary-category">
        <div className="secondary-category-header">{category.name}</div>
        <div className="secondary-category-body">
          {
            _.map(category.children, childCategory =>
              <TertiaryCategory key={childCategory.id} category={childCategory}/>)
          }
        </div>
      </div>
    )
  }
}

interface TopCategoryProps {
  topCategory?: catalog.Category;
}

interface TopCategoryState {
  childCategories: catalog.Category[];
}

class TopCategory extends React.Component<TopCategoryProps, TopCategoryState> {
  public constructor(props: Readonly<TopCategoryProps>) {
    super(props)

    this.state = {
      childCategories: [],
    }
  }

  public componentDidMount(): void {
    this.refreshChildCategories()
  }

  public componentDidUpdate(prevProps: Readonly<TopCategoryProps>,
                            prevState: Readonly<TopCategoryState>, snapshot?: any): void {

    if (prevProps.topCategory?.id !== this.props.topCategory?.id) {
      this.refreshChildCategories()
    }
  }

  public render() {
    const { childCategories } = this.state
    return (
      <Scroll className="top-category-content">
        {
          _.map(childCategories, category =>
            <SecondaryCategory key={category.id} category={category}/>)
        }
      </Scroll>
    )
  }

  private refreshChildCategories() {
    const { topCategory } = this.props
    if (topCategory && topCategory.id) {
      catalog.CategoryServiceV1.getCategories().parentId(topCategory.id).level(2).list()
        .then(childCategories => this.setState({ childCategories }))
    }
  }
}


interface CategoriesState {
  selectedCategory?: catalog.Category;
  topCategories: catalog.Category[];
}

export class Categories extends React.Component<any, CategoriesState> {

  constructor(props: Readonly<any>) {
    super(props)
    this.state = {
      topCategories: [],
    }
  }

  public componentDidMount(): void {
    this.refreshTopCategories()
  }

  public render() {

    const { topCategories, selectedCategory } = this.state
    return (
      <>
        <div className="categories">
          <NavBar>分类</NavBar>
          <div className="categories-content">
            <div className="top-categories">
              {
                _.map(topCategories, topCategory =>
                  <div key={topCategory.id}
                       className={classNames("top-category",
                         {
                           "top-category-selected": selectedCategory && topCategory.id === selectedCategory.id,
                         })}
                       onClick={() => this.setState({ selectedCategory: topCategory })}>{topCategory.name}</div>)
              }
            </div>
            <TopCategory topCategory={selectedCategory}/>
          </div>
        </div>
      </>
    )
  }


  private refreshTopCategories() {
    catalog
      .CategoryServiceV1.getCategories()
      .list()
      .then(topCategories => {
        this.setState({
          topCategories,
          selectedCategory: topCategories[0],
        })
      })
  }
}
